import axios from 'axios';
import { notification } from 'ant-design-vue';

const instance = axios.create({
  baseURL: (window as any).config.baseURL,
  timeout: 300000, // 60000
});

instance.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
instance.defaults.headers.delete['Content-Type'] = 'application/json;charset=utf-8';

instance.interceptors.request.use((config) => {
  return config;
}),
  (err: unknown) => {
    Promise.reject(err);
  };

instance.interceptors.response.use(
  (res) => {
    const { code, type } = res.data;
    // 处理文件下载类接口
    if (typeof code !== 'number') {
      if (type === 'application/json') {
        const reader = new FileReader();
        reader.onload = (e: any) => {
          const { msg } = JSON.parse(e.target.result);
          notification.error({ message: '错误', description: msg });
        };
        reader.readAsText(res.data);
        return Promise.reject('error');
      } else {
        return res;
      }
    } else {
      if (code === 401) {
        notification.error({
          message: '错误',
          description: '用户认证失效，请重新登录',
        });
      } else {
        return res.data;
      }
    }
  },
  (err: any) => {
    notification.error({
      message: '错误',
      description: err.response.data.message,
    });
    return Promise.reject('error');
  },
);

export default instance;
